--- 模块功能：MQTT客户端处理框架
-- @author openLuat
-- @module mqtt.mqttTask
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.28
module(..., package.seeall)

require "misc"
require "mqtt"
require "mqttInMsgQuakeInfoRel"
require "mqttOutMsgQuakeRel"
require "nvm"
require "logGenerator"
-- 初始化nvm获取配置参数
nvm.init("config.lua", true)
-- 参数初始化
local ready, uname_mqtt, pwd_mqtt, mqtthost, topic, eqrTopic, port, mqttClientId =
    false, nvm.get("centerConfig")[7], nvm.get("centerConfig")[8],
    nvm.get("centerConfig")[10], nvm.get("centerConfig")[11],
    nvm.get("centerConfig")[12], nvm.get("centerConfig")[14],
    nvm.get("centerConfig")[6]

--- MQTT连接是否处于激活状态
-- @return 激活状态返回true，非激活状态返回false
-- @usage mqttTask.isReady()
function isReady() return ready end
-- 组装主题列表
local function assembleTopic()
    local topicList = {}
    topicList[topic] = 0
    topicList[eqrTopic] = 1
    topicList["EEW/JSON/DRILL/KSCONNTEST"] = 0
    return topicList
end

-- 启动MQTT客户端任务
function startMQTTClient(clientNo)
    sys.taskInit(function()
        local retryConnectCnt, retryStartDevCnt, topicSubscriptionFailCnt,
              topicSubscriptionSusCnt, logInfo, errorInfo, sysTime =
            0, 0, 0, 0, "", "", ""
        sysTime = string.format("%04d-%02d-%02d %02d:%02d:%02d",
                                os.date("*t").year, os.date("*t").month,
                                os.date("*t").day, os.date("*t").hour,
                                os.date("*t").min, os.date("*t").sec)
        while true do
            if rtos.get_fs_free_size() < 921600 then

                if rtos.remove_dir(logGenerator.LOG_DIR_PATH) then
                    logInfo = ""
                    logInfo = "[" .. sysTime .. "]" ..
                                  "[日志文件删除成功！]\n"
                    logGenerator.generateLogTask(logInfo, "log")
                else
                    errorInfo = ""
                    errorInfo = "[" .. sysTime .. "]" ..
                                    "[日志文件删除失败！]\n"
                    logGenerator.generateLogTask(errorInfo, "log")
                end
            end
            if not socket.isReady() then
                retryConnectCnt = 0
                -- 等待网络环境准备就绪，超时时间是5分钟
                sys.waitUntil("IP_READY_IND", 300000)
                retryStartDevCnt = retryStartDevCnt + 1
            end
            if socket.isReady() then
                retryStartDevCnt = 0
                -- 创建一个MQTT客户端
                -- log.info("clientNo", clientNo, "uname_mqtt", uname_mqtt, "pwd_mqtt", pwd_mqtt)
                log.info("mqttClientId:", mqttClientId)
                local mqttRClient, mqtthostArray, host, transport =
                    mqtt.client(mqttClientId, 120, uname_mqtt, pwd_mqtt, nil,
                                nil, "3.1.1"), string.split(mqtthost, "://")
                host = mqtthostArray[1]
                transport = mqtthostArray[2]
                log.info("host", host, "transport", transport)
                -- 阻塞执行MQTT CONNECT动作，直至成功
                -- 如果使用ssl连接，打开mqttRClient:connect("lbsmqtt.airm2m.com",1884,"tcp_ssl",{caCert="ca.crt"})，根据自己的需求配置
                -- mqttRClient:connect("lbsmqtt.airm2m.com",1884,"tcp_ssl",{caCert="ca.crt"})
                if mqttRClient:connect(transport, tonumber(port), host) then
                    sysTime = string.format("%04d-%02d-%02d %02d:%02d:%02d",
                                            os.date("*t").year,
                                            os.date("*t").month,
                                            os.date("*t").day,
                                            os.date("*t").hour,
                                            os.date("*t").min, os.date("*t").sec)
                    logInfo = ""
                    if topicSubscriptionFailCnt < 1 and topicSubscriptionSusCnt <
                        1 then
                        logInfo = "[" .. sysTime .. "]" ..
                                      "[注册中心mq连接成功！]\n" ..
                                      "[mq信息:]" .. "mqHost:" .. host ..
                                      ",mqTransport:" .. transport ..
                                      ",mq用户名:" .. uname_mqtt ..
                                      "mq登录密码:" .. pwd_mqtt .. "\n"
                        logGenerator.generateLogTask(logInfo, "log")
                    end

                    retryConnectCnt = 0
                    ready = true
                    log.info("topicmqttTaskQuakeInfoRel:", topic)
                    -- 订阅主题
                    if mqttRClient:subscribe(assembleTopic()) then
                        topicSubscriptionFailCnt = 0
                        if topicSubscriptionSusCnt < 1 then
                            logInfo = ""
                            logInfo = "[" .. sysTime .. "]" ..
                                          "[注册中心mq主题订阅成功！]\n" ..
                                          "[主题信息:]" .. "topic:" .. topic ..
                                          "\n"
                            logGenerator.generateLogTask(logInfo, "log")
                        end
                        topicSubscriptionSusCnt = topicSubscriptionSusCnt + 1
                        -- 循环处理接收和发送的数据
                        while true do
                            log.info("TEST")
                            if not mqttInMsgQuakeInfoRel.proc(mqttRClient) then
                                log.error(
                                    "mqttInMsgQuakeInfoRel.mqttInMsg.proc error")
                                log.info("TEST1")
                                break
                            end
                            if not mqttOutMsgQuakeRel.proc(mqttRClient) then
                                log.error(
                                    "mqttOutMsgQuakeRel.mqttOutnMsg.proc error")
                                log.info("TEST2")
                                break
                            end
                        end
                    else
                        topicSubscriptionSusCnt = 0
                        log.info("topicSubscriptionWrong")
                        if topicSubscriptionFailCnt < 1 then
                            logInfo = "[" .. sysTime .. "]" ..
                                          "[注册中心mq主题订阅失败！]\n"
                            logGenerator.generateLogTask(logInfo, "log")
                        end
                        topicSubscriptionFailCnt = topicSubscriptionFailCnt + 1
                    end
                    ready = false
                else
                    retryConnectCnt = retryConnectCnt + 1
                end
                -- 断开MQTT连接
                mqttRClient:disconnect()
                logInfo = "[" .. sysTime .. "]" ..
                              "[注册中心mq连接断开！]\n"
                logGenerator.generateLogTask(logInfo, "log")
                log.info("台网中心mqtt连接断开!")
                if retryConnectCnt >= 5 then
                    link.shut()
                    retryConnectCnt = 0
                    log.info("retryConnectCnt111", retryConnectCnt)
                end
                sys.wait(5000)
            else
                -- 进入飞行模式，20秒之后，退出飞行模式
                net.switchFly(true)
                sys.wait(20000)
                net.switchFly(false)
            end
            if retryStartDevCnt >= 7 then
                retryStartDevCnt = 0
                sys.restart("重启设备！")
            end
        end
    end)
end
